package com.allwees.bs.task.misc;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 *
 * 把数据库中表datetime类型字段统一修改为timestamp
 * @Author Daniel
 * @Version 1.0.0
 * @Description
 * @CreateTime 2020/11/5 13:33
 */
@Slf4j
@Service
public class UpdateTableColumnToTimestamp {

    @Resource
    private UpdateTableService updateTableService;

    @XxlJob(value = "updateTableColumnToTimestamp")
    public ReturnT<String> run(String s) {
        if ("truncate".equals(s)) {
            new Thread(this::truncateDatetime).start();
        } else if ("addhours".equals(s)) {
            new Thread(this::add7Hours).start();
        }

        return ReturnT.SUCCESS;
    }

    /**
     * 数据库中所有的datetime(6) -> datetime
     */
    private void truncateDatetime(){
        log.info("==========================>start truncate datetime...");
        String truncate_datetime = "alter table %s modify %s datetime";
        List<Map<String,Object>> maps = updateTableService.columnsOfDatetimeWithPrecision();
        maps.forEach(map -> {
            String sql = String.format(truncate_datetime, map.get("table_name"), map.get("column_name"));
            if("no".equalsIgnoreCase(map.get("is_nullable").toString())){
                sql += " not null";
            }
            log.info(sql);
            updateTableService.update(sql);
        });
        log.info("==========================>end truncate datetime...");
    }

    /**
     * 数据库中所有的时间字段修增加七小时
     */
    private void add7Hours(){
        log.info("==========================>start add 7 hours...");
        String add_hours = "update %s set %s = date_add(%s, interval 7 hour)";
        List<Map<String,Object>> maps = updateTableService.columnsOfDatetime();
        maps.forEach(map -> {
            Object column_name = map.get("column_name");
            String sql = String.format(add_hours, map.get("table_name"), column_name,column_name);
            log.info(sql);
            updateTableService.update(sql);
        });
        log.info("==========================>end add 7 hours...");
    }
}
